package com.ely.coupon.auth.service.impl;

import com.ely.coupon.auth.service.AuthService;
import com.ely.coupon.auth.service.JwtService;
import com.ely.coupon.common.core.ex.ServiceException;
import com.ely.coupon.common.core.result.ResponseCode;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class AuthServiceImpl implements AuthService {
    @Resource
    private AuthenticationManager authenticationManager;
    @Resource
    private JwtService jwtService;

    @Override
    public String auth(String username, String password) {
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username, password);
        Authentication authenticate = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
        if (authenticate == null) {
            throw new ServiceException(ResponseCode.AUTH_ERROR);
        }
        User user = (User) authenticate.getPrincipal();
        return jwtService.generateToken(user);

    }
}
